document.addEventListener('DOMContentLoaded', function() {
    // Get DOM elements
    const templateButtons = document.querySelectorAll('.template-btn');
    const teacherNameInput = document.getElementById('teacher-name');
    const studentNameInput = document.getElementById('student-name');
    const messageInput = document.getElementById('message');
    const decorationSelect = document.getElementById('decoration');
    const previewBtn = document.getElementById('preview-btn');
    const exportBtn = document.getElementById('export-btn');
    const shareBtn = document.getElementById('share-btn');
    const resetBtn = document.getElementById('reset-btn');
    
    const previewTeacherName = document.getElementById('preview-teacher-name');
    const previewStudentName = document.getElementById('preview-student-name');
    const previewMessage = document.getElementById('preview-message');
    const previewMessageEn = document.getElementById('preview-message-en');
    const decorationDisplay = document.getElementById('decoration-display');
    const thankYouCard = document.getElementById('thank-you-card');
    
    // Decoration icons mapping
    const decorationIcons = {
        apple: '🍎',
        book: '📚',
        flower: '🌸',
        graduation: '🎓'
    };
    
    // Default messages
    const defaultMessages = {
        zh: "感谢您的辛勤教导和无私奉献。您点燃了我们心中的知识之光，引导我们走向成功的道路。",
        en: "Thank you for your dedication and selfless contribution. You have ignited the light of knowledge in our hearts and guided us on the path to success."
    };
    
    // Template selection
    templateButtons.forEach(button => {
        button.addEventListener('click', function() {
            // Remove active class from all buttons
            templateButtons.forEach(btn => btn.classList.remove('active'));
            
            // Add active class to clicked button
            this.classList.add('active');
            
            // Get template name
            const template = this.getAttribute('data-template');
            
            // Update card template
            thankYouCard.className = 'thank-you-card ' + template;
        });
    });
    
    // Update preview function
    function updatePreview() {
        // Update teacher name
        const teacherName = teacherNameInput.value.trim();
        previewTeacherName.textContent = teacherName || '[老师姓名]';
        
        // Update student name
        const studentName = studentNameInput.value.trim();
        previewStudentName.textContent = studentName || '[您的姓名]';
        
        // Update message
        const message = messageInput.value.trim();
        if (message) {
            previewMessage.textContent = message;
            // For simplicity, we'll use the same message for English
            // In a real implementation, you might want separate fields
            previewMessageEn.textContent = message;
        } else {
            previewMessage.textContent = defaultMessages.zh;
            previewMessageEn.textContent = defaultMessages.en;
        }
        
        // Update decoration
        const decoration = decorationSelect.value;
        decorationDisplay.textContent = decorationIcons[decoration];
    }
    
    // Add event listeners for real-time preview
    teacherNameInput.addEventListener('input', updatePreview);
    studentNameInput.addEventListener('input', updatePreview);
    messageInput.addEventListener('input', updatePreview);
    decorationSelect.addEventListener('change', updatePreview);
    
    // Preview button (in case we want to trigger manually)
    previewBtn.addEventListener('click', function() {
        updatePreview();
        
        // Add a nice animation effect
        thankYouCard.style.transform = 'scale(0.95)';
        setTimeout(() => {
            thankYouCard.style.transform = '';
        }, 300);
    });
    
    // Export button
    exportBtn.addEventListener('click', function() {
        // Check if html2canvas is available
        if (typeof html2canvas === 'undefined') {
            alert('导出功能加载中，请稍后再试...\nExport functionality is loading, please try again...');
            // Try to load the library dynamically
            const script = document.createElement('script');
            script.src = 'https://cdn.jsdelivr.net/npm/html2canvas@1.4.1/dist/html2canvas.min.js';
            script.onload = function() {
                alert('导出功能已加载完成，请再次点击导出按钮。\nExport functionality has been loaded, please click the export button again.');
            };
            document.head.appendChild(script);
            return;
        }
        
        // Update preview first to ensure all content is current
        updatePreview();
        
        // Temporarily add a class for export styling
        thankYouCard.classList.add('exporting');
        
        // Use html2canvas to capture the card
        html2canvas(thankYouCard, {
            backgroundColor: null,
            scale: 2, // Higher quality export
            useCORS: true,
            logging: false
        }).then(canvas => {
            // Remove the export class
            thankYouCard.classList.remove('exporting');
            
            // Create download link
            const link = document.createElement('a');
            link.download = 'teacher-thank-you-card.png';
            link.href = canvas.toDataURL('image/png');
            
            // Trigger download
            link.click();
            
            // Show success message
            alert('卡片已成功导出为图片！\nCard exported successfully as image!');
        }).catch(error => {
            // Remove the export class in case of error
            thankYouCard.classList.remove('exporting');
            
            // Show error message
            alert('导出失败，请重试。\nExport failed, please try again.\nError: ' + error.message);
        });
    });
    
    // Share button
    shareBtn.addEventListener('click', function() {
        // Update preview first to ensure all content is current
        updatePreview();
        
        // Check if html2canvas is available
        if (typeof html2canvas === 'undefined') {
            alert('分享功能加载中，请稍后再试...\nShare functionality is loading, please try again...');
            return;
        }
        
        // Temporarily add a class for export styling
        thankYouCard.classList.add('exporting');
        
        // Use html2canvas to capture the card
        html2canvas(thankYouCard, {
            backgroundColor: null,
            scale: 2, // Higher quality export
            useCORS: true,
            logging: false
        }).then(canvas => {
            // Remove the export class
            thankYouCard.classList.remove('exporting');
            
            // Convert canvas to blob
            canvas.toBlob(function(blob) {
                // Create share data
                const shareData = {
                    title: '教师节感恩卡片 - Teacher\'s Day Thank You Card',
                    text: `学生 ${studentNameInput.value.trim() || '匿名'} 为 ${teacherNameInput.value.trim() || '敬爱的老师'} 制作的教师节感恩卡片`,
                    files: [new File([blob], 'teacher-thank-you-card.png', { type: 'image/png' })]
                };
                
                // Try to use Web Share API
                if (navigator.share && navigator.canShare(shareData)) {
                    navigator.share(shareData)
                        .then(() => {
                            alert('分享成功！\nShare successful!');
                        })
                        .catch(error => {
                            if (error.name !== 'AbortError') {
                                // Fallback to copy link
                                fallbackShare(canvas);
                            }
                        });
                } else {
                    // Fallback for browsers that don't support Web Share API
                    fallbackShare(canvas);
                }
            }, 'image/png');
        }).catch(error => {
            // Remove the export class in case of error
            thankYouCard.classList.remove('exporting');
            
            // Show error message
            alert('分享失败，请重试。\nShare failed, please try again.\nError: ' + error.message);
        });
    });
    
    // Fallback share function
    function fallbackShare(canvas) {
        // Create a modal for sharing options
        const shareModal = document.createElement('div');
        shareModal.style.cssText = `
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0,0,0,0.8);
            display: flex;
            justify-content: center;
            align-items: center;
            z-index: 1000;
        `;
        
        const shareContent = document.createElement('div');
        shareContent.style.cssText = `
            background: white;
            padding: 30px;
            border-radius: 15px;
            text-align: center;
            max-width: 400px;
            width: 90%;
        `;
        
        shareContent.innerHTML = `
            <h3 style="margin-bottom: 20px;">分享选项 | Share Options</h3>
            <div style="display: flex; flex-direction: column; gap: 15px;">
                <button id="download-share" style="padding: 12px; background: #667eea; color: white; border: none; border-radius: 8px; cursor: pointer;">
                    下载图片后分享 | Download and Share
                </button>
                <button id="copy-link" style="padding: 12px; background: #43e97b; color: white; border: none; border-radius: 8px; cursor: pointer;">
                    复制图片链接 | Copy Image Link
                </button>
                <button id="close-share" style="padding: 12px; background: #f5576c; color: white; border: none; border-radius: 8px; cursor: pointer;">
                    取消 | Cancel
                </button>
            </div>
        `;
        
        shareModal.appendChild(shareContent);
        document.body.appendChild(shareModal);
        
        // Event listeners for share options
        document.getElementById('download-share').addEventListener('click', function() {
            // Download the image
            const link = document.createElement('a');
            link.download = 'teacher-thank-you-card.png';
            link.href = canvas.toDataURL('image/png');
            link.click();
            
            // Close modal
            document.body.removeChild(shareModal);
            
            alert('图片已下载，您可以手动分享给朋友！\nImage downloaded, you can share it manually!');
        });
        
        document.getElementById('copy-link').addEventListener('click', function() {
            // Copy image data URL to clipboard
            const imageDataUrl = canvas.toDataURL('image/png');
            
            navigator.clipboard.writeText(imageDataUrl)
                .then(() => {
                    alert('图片链接已复制到剪贴板！\nImage link copied to clipboard!');
                })
                .catch(() => {
                    // Fallback for older browsers
                    const textArea = document.createElement('textarea');
                    textArea.value = imageDataUrl;
                    document.body.appendChild(textArea);
                    textArea.select();
                    document.execCommand('copy');
                    document.body.removeChild(textArea);
                    alert('图片链接已复制到剪贴板！\nImage link copied to clipboard!');
                });
            
            // Close modal
            document.body.removeChild(shareModal);
        });
        
        document.getElementById('close-share').addEventListener('click', function() {
            document.body.removeChild(shareModal);
        });
        
        // Close modal when clicking outside
        shareModal.addEventListener('click', function(e) {
            if (e.target === shareModal) {
                document.body.removeChild(shareModal);
            }
        });
    }
    
    // Reset button
    resetBtn.addEventListener('click', function() {
        // Reset form inputs
        teacherNameInput.value = '';
        studentNameInput.value = '';
        messageInput.value = '';
        decorationSelect.value = 'apple';
        
        // Reset preview
        updatePreview();
        
        // Reset template to classic
        templateButtons.forEach(btn => btn.classList.remove('active'));
        document.querySelector('.template-btn[data-template="classic"]').classList.add('active');
        thankYouCard.className = 'thank-you-card classic';
        
        // Add reset animation
        thankYouCard.style.transform = 'rotate(5deg)';
        setTimeout(() => {
            thankYouCard.style.transform = '';
        }, 300);
    });
    
    // Initialize preview
    updatePreview();
    
    // Show usage instructions on page load
    window.addEventListener('load', function() {
        setTimeout(function() {
            alert('教师节卡片制作指南：\n1. 选择模板并填写信息\n2. 点击"预览卡片"查看效果\n3. 点击"导出图片"保存作品\n注：首次使用需等待3秒加载资源\n\nTeacher\'s Day Card Creation Guide:\n1. Choose a template and fill in information\n2. Click "Preview Card" to see the effect\n3. Click "Export Image" to save your work\nNote: Please wait 3 seconds for initial loading');
        }, 1000);
    });
    
    // Check if html2canvas is loaded, if not show a message
    setTimeout(function() {
        if (typeof html2canvas === 'undefined') {
            console.log('html2canvas library is still loading...');
        }
    }, 1000);
});